import React, { FC } from 'react';
import { FormInstance } from 'antd/lib/form';
import ProTable, { ProColumns } from '@/components/ProTable';
import useHoxModel from '../../../../useHoxModel';
import { AddDoorGroupType } from '../../../../API';
import { useUnmount, useUpdateEffect } from 'ahooks';
import styles from './index.less';
import { pick } from 'lodash';

const AddForm: FC<{
  formRef: React.MutableRefObject<FormInstance | undefined>;
  isEdit?: boolean;
}> = ({ formRef, isEdit }) => {
  const { doorGroupInfo, dispatch } = useHoxModel((model) => [model.doorGroupInfo]);
  useUnmount(() => {
    formRef.current?.resetFields();
    dispatch({ doorGroupInfo: {} });
  });

  useUpdateEffect(() => {
    if (doorGroupInfo && JSON.stringify(doorGroupInfo) !== '{}') {
      const fields = pick(doorGroupInfo, ['name', 'rec']);
      formRef.current?.setFieldsValue(fields);
    }
  }, [doorGroupInfo]);

  const columns: ProColumns<AddDoorGroupType>[] = [
    {
      title: '门组名称:',
      dataIndex: 'name',
      rules: [
        {
          required: true,
        },
      ],
    },
    {
      title: '备注:',
      dataIndex: 'rec',
      valueType: 'textarea',
    },
  ];
  const initialValues = (doorGroupInfo && pick(doorGroupInfo, ['name', 'rec'])) || {};
  return (
    <div className={styles['add-form']}>
      <ProTable<AddDoorGroupType>
        form={{ layout: 'vertical', autoComplete: 'off', initialValues }}
        columns={columns}
        type={'form'}
        formRef={formRef}
      />
    </div>
  );
};
export default AddForm;
